package com.zou.application.controller.admin;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONObject;
import com.zou.application.dao.ProductEntityMapper;
import com.zou.application.entity.ProductEntity;
import com.zou.application.utils.StringUtils;

@Controller
@RequestMapping("/admin/product")
public class ProductController {
	
	@Autowired
	private ProductEntityMapper productDao;
	
	@RequestMapping("/addProductPage")
	public String addProductPage(){
		return "/admin/product/product_add";
	}
	
	@RequestMapping("/addProduct")
	public String addProduct(HttpServletRequest request,ProductEntity product){
		try {
			if(product != null){
				product.setCreater("admin");
				product.setCreateTime(new Date());
				product.setStatus((short)1);
				product.setIsDelete((short)0);
				productDao.insert(product);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "redirect:/admin/product/productList";
	}
	
	@RequestMapping("/productList")
	public ModelAndView productList(HttpServletRequest request){
		ModelAndView mv = new ModelAndView();
		Map<String, Object> param = new HashMap<String, Object>();
		List<ProductEntity> productEntities = productDao.listByMap(param);
		mv.addObject("products",productEntities);
		mv.setViewName("/admin/product/product_list");
		return mv;
	}
	
	@RequestMapping("/delete")
	@ResponseBody
	public JSONObject delete(HttpServletRequest request){
		JSONObject result = new JSONObject();
		String productId = request.getParameter("productId");
		if(StringUtils.isEmpty(productId)){
			result.put("code","100");
			result.put("msg","");
			return result;
		}
		try {
			productDao.delete(Integer.parseInt(productId));
			result.put("code","200");
			result.put("msg","删除成功");
		} catch (Exception e) {
			e.printStackTrace();
			result.put("code","100");
			result.put("msg","系统异常");
		}
		return result;
	}
}
